package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
)

func main() {
	//str := "一篇诗，一斗酒，一曲长歌，一剑天涯"
	//fmt.Println("加密前：", str)
	//data, _ := RsaEncryptString(str)
	//fmt.Println("加密后：", data)
	data := "RrBWhyA0YZp9nTtHbVOuoyrl26JkX9Ln/6SJAGpTIlDohZA5THL1I2+JySMzDFJitSNlnCT1s4+naETBja93JtBTgOlOr3RuX60NavCwOb4JrBg7wdobHiS/knwx8H4qiKzko2lVYYfzQVonwtaivlPXRvDycZ8Ks7yQNOjnTJ8="
	origData, err := RsaDecryptString(data)
	if nil != err {
		fmt.Printf("err:%v \n", err)
	}
	fmt.Println("解密后：", string(origData))
}

var (
	privateKey []byte
	publicKey  []byte
)

func init() {
	var err error
	publicKey, err = ioutil.ReadFile("d:/public1.pem")
	if nil != err {
		os.Exit(-1)
	}

	privateKey, err = ioutil.ReadFile("d:/private1.pem")
	if nil != err {
		os.Exit(-1)
	}

}

// 加密字节数组，返回字节数组
func RsaEncrypt(origData []byte) ([]byte, error) {
	block, _ := pem.Decode(publicKey)
	if nil == block {
		return nil, errors.New("public key error")
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if nil != err {
		return nil, err
	}
	pub := pubInterface.(*rsa.PublicKey)
	return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
}

// 解密字节数组，返回字节数组
func RsaDecrypt(ciphertext []byte) ([]byte, error) {
	block, _ := pem.Decode(privateKey)
	if nil == block {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS8PrivateKey(block.Bytes) //x509.ParsePKCS1PrivateKey(block.Bytes)
	//x509.ParsePKCS1PrivateKey(block.Bytes)
	if nil != err {
		return nil, err
	}
	return rsa.DecryptPKCS1v15(rand.Reader, priv.(*rsa.PrivateKey), ciphertext)
}

// 加密字符串，返回 base64 处理的字符串
func RsaEncryptString(origData string) (string, error) {

	cipherArr, err := RsaEncrypt([]byte(origData))
	if nil != err {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(cipherArr), nil
}

func RsaDecryptString(cipherText string) (string, error) {
	cipherArr, _ := base64.StdEncoding.DecodeString(cipherText)
	originalArr, err := RsaDecrypt(cipherArr)
	if nil != err {
		return "", err
	}
	return string(originalArr), nil
}
